<?php

class Signup extends Controller {

	function index()
	{
		parent::Controller();
		$this->load->model('usermodel');
		$this->load->library('form_validation');
		$this->load->plugin('captcha');
		$this->load->helper('url');
		
		/* Facebook Connect */	
	    $this->load->library('fb_connect');
		$data = array(
						'facebook'		=> $this->fb_connect->fb,
						'fbSession'		=> $this->fb_connect->fbSession,
						'user'			=> $this->fb_connect->user,
						'uid'			=> $this->fb_connect->user_id,
						'fbLogoutURL'	=> $this->fb_connect->fbLogoutURL,
						'fbLoginURL'	=> $this->fb_connect->fbLoginURL,	
						'base_url'		=> site_url('signup/facebook'),
						'appkey'		=> $this->fb_connect->appkey,
					   );
		/* End Facebook Connect */
		
		$data['titlebar'] = 'Panoramap - Signup';
		$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|matches[repassword]|xss_clean');
		$this->form_validation->set_rules('repassword', 'Password Confirmation', 'trim|required|xss_clean');
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email|xss_clean');

		if($this->session->userdata('userId') != null) redirect('profile'); //ถ้า login อยู่จะมาหน้านี้ไม่ได้

		if($this->form_validation->run() == FALSE)
		{
			$this->load->view('signup_view', $data);
		}
		else
		{
			$newUserValues = $this->usermodel->newUser($_POST);
			if($newUserValues == true)
			{
				$this->sendConfirmEmail($this->input->post('username'), $this->input->post('email'));
				$data['titlebar'] = 'Panoramap - การสมัครสมาชิกยังไม่เสร็จสมบูรณ์!';
				$data['Email'] = $this->input->post('email');
				$this->load->view('signup_success_view', $data);
			}
			else
			{
				$data['error'] = 'เราพบปัญหาในการลงทะเบียน! อีเมลนี้ถูกใช้ในการลงทะเบียนไปแล้ว.';
				$this->load->view('signup_error_view', $data);
			}
		}
	}

	function sendConfirmEmail($username, $email)
		{
				$this->load->library('email');
				$confirmKey = md5(time());
				$confirmText = base_url() . 'signup/confirm/' . $confirmKey;
				//Set the user activation key
				$this->usermodel->setUserActivationKey($email, $confirmKey);
				$this->email->from('no-reply@panoramap.in.th', 'Panoramap');
				$this->email->to($email);
				$this->email->subject('Activate your account');
				$this->email->message(nl2br('Please click link to activate your account: '.$confirmText.'       Activation Key: '.$confirmKey));
				$this->email->send();
		}

	function confirm($confirmKey)
		{
				//Load the user model
				$this->load->model('usermodel');
				//setUserActive
				$this->usermodel->setUserActive($confirmKey);
				//Set the flash data
				$this->session->set_flashdata('success', 'Account activate complete.');
				//go the login page
				redirect('home');
		}

/*
	   function _facebook_validate($uid = 0) {
		   $this->load->model('usermodel');
			//this query basically sees if the users facebook user id is associated with a user.
			$bQry = $this->usermodel->validate_user_facebook($uid);
			
			if($bQry) { // if the user's credentials validated...
				$data = array(
								'user_id' => $uid,
								'is_logged_in' => true, 
								'list_type' => 'hot'
				);
				
				$this->session->set_userdata($data);
			 
				$uri_var = $this->uri->segment(3);
				
				if (strlen($uri_var) > 0 ){
					$url_location = $uri_var;
					$url_location = str_replace('-', '/', $url_location);
					redirect($url_location);			
				} else{
					redirect('/login');
				}
				 
			} else {
				// incorrect username or password
				$data = array();
				$data["login_failed"] = TRUE;
				$this->index($data);
			}
	   }
*/

	   function facebook() {
			//1. Check to see if the facebook session has been declared
			$this->load->model('usermodel');
			$this->load->library('fb_connect');
			
			if(!$this->fb_connect->fbSession) {
				//2. If No, bounce back to login
				$this->index();
			} else {
				
				$fb_uid = $this->fb_connect->user_id;
				$fb_usr = $this->fb_connect->user;
				
				if($fb_uid != false) {
					//3. If yes, see if the facebook id is associated with any existing account
					$usr = $this->usermodel->get_user_by_fb_uid($fb_uid);
					
					if( is_array($usr) && count($usr) == 1) {
						$usr = $usr[0]; //the model returns an object array, so get the first elemet of it which contains all of the data we need.
						//3.a. if yes, log the person in
						echo "Logging in via facebook...";
						//$this->_facebook_validate($usr->user_id);
					} else {
						//3.b. if no, register the new user.
						//echo "Creating a new account...";
						$fname = $fb_usr["first_name"]; 
						$lname = $fb_usr["last_name"];
						$fullname = $fb_usr["name"];
						$pwd = ''; //left blank so user can modify this later
						$email = $fb_usr["email"];
						
						$db_values = array (
						 'user_id' => "fb:".$fb_uid,
						 'fb_uid' => "fb:".$fb_uid,
						 'full_name' => $fullname,
						 'pwd' => "",
						 'email' => $email,
						 'titlebar' => "Join Panoramap It's Easy!",
						 );
						 
						//data ready, try to create the new user 
						/*
						if($query = $this->usermodel->create_user($db_values) ) {
							//$data['account_created'] = true;
							//log user in
							//$this->_facebook_validate($db_values["user_id"]);
							echo "Create user";
						
						} else {
							//Did not work, go back to login page
							//$this->index();
							$data['error'] = 'Signup with Facebook Error!';
							$this->load->view('signup_error_view', $data);
						}	
						*/

						$this->load->view('join_fb_view', $db_values);

					}
				} 
			}
	   } 


}
/* End of file signup.php*/
/* Location: application/controllers/signup.php */